package org.kits.service;

import org.springframework.stereotype.Component;

/**
 * 通过redis对某一段时间内用户行为进行限制
 * 指定用户 user_id 的某个行为 action_key 在特定的时间内 period 只允许发生一定的次
 * @author SKyOne
 * @create 2020-03-08 15:16
 */
@Component
public class SimpleRateLimiter {
   /* private Jedis jedis;

    public SimpleRateLimiter(Jedis jedis){
        this.jedis = jedis;
    }

    public boolean isActionAllowed(String userId,String actionKey,int period,int maxCount){
        String key = String.format("hist:%s:%s", userId,actionKey);
        long nowTs = System.currentTimeMillis();
        Pipeline pipe = jedis.pipelined();
        pipe.multi();
        pipe.zadd(key, nowTs,""+nowTs);
        pipe.zremrangeByScore(key,0,nowTs-period*1000);
        Response<Long> count = pipe.zcard(key);
        pipe.expire(key,period+1);
        pipe.exec();
        pipe.close();
        return count.get()<=maxCount;
    }*/

    public static void main(String[] args) {
        /*Jedis jedis = new Jedis();
        SimpleRateLimiter limiter = new SimpleRateLimiter(jedis);
        for (int i = 0; i < 20; i++) {
            System.out.println(limiter.isActionAllowed("test","tester",60,5));
        }

        System.out.println("test");*/
    }
}
